import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-04 17:55
 *  */
public class CodeGenerator {



    static final String RBAC = "rbac";
    static final String PROD = "prod";

    static String [] rbacTables = {"tb_admin_login_log","tb_admin_menu",
    "tb_admin_op_log","tb_admin_operation","tb_admin_privilege",
    "tb_admin_privilege_menu","tb_admin_privilege_operation",
    "tb_admin_role","tb_admin_role_privilege","tb_admin_user",
    "tb_admin_user_role"};
    static String [] rbacViews = {"admin_privilege_view","admin_url_privilege_role_view","admin_user_view"};



    static String [] prodTable = {"tb_customer","tb_customer_addr","tb_customer_balance_log","tb_customer_info",
                                "tb_customer_level_info","tb_customer_login_log","tb_customer_point_log",
                                "tb_order_cart","tb_order_cart_item","tb_order_item_detail","tb_order_master",
                                "tb_prod_attr","tb_prod_attr_option","tb_prod_brand","tb_prod_cate","tb_prod_cate_brand",
                                "tb_prod_comment","tb_prod_sku","tb_prod_sku_attr_option","tb_prod_sku_image",
                                "tb_prod_sku_spec_option","tb_prod_spec","tb_prod_spec_group","tb_prod_spec_option",
                                "tb_prod_spu","tb_prod_spu_image","tb_prod_supplier_info","tb_shipping_info",
                                "tb_warehouse_info","tb_warehouse_product"
    };

    static String [] prodViews = {"spu_view","sku_view","order_item_detail_view"};

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        /*
        *  对MP的自动生成代码的配置请参考官网的:
        *  https://mp.baomidou.com/config/generator-config.html#基本配置
        * */

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/emall-dao/src/main/java");
        gc.setAuthor("xiaozai");
        gc.setOpen(false);
        //实体属性 Swagger2 注解
        gc.setSwagger2(true);
        gc.setActiveRecord(false);
        gc.setFileOverride(false);
        gc.setControllerName("");

        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/emall?useUnicode=true&useSSL=false&characterEncoding=utf8");

        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setTypeConvert(new MySqlTypeConvertCustom());

        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        String module = scanner("模块名");
        pc.setModuleName(module);
        pc.setParent("org.jet.emall");
        pc.setEntity("po");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        //String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
         String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/emall-dao/src/main/resources/org/jet/emall/" + pc.getModuleName()
                        + "/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        String r1 = scanner("需要生成service?y/n");
        String y = "y";
        if(!y.equals(r1.toLowerCase())){
            templateConfig.setServiceImpl("");
            templateConfig.setService("");
        }
        String r2 = scanner("需要生成controller?y/n");
        if(!y.equals(r2.toLowerCase())){
            templateConfig.setController("");
        }


        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);

        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        String r3 = scanner("t-表 还是 v-视图 ? t/v");
        String t = "t";

        if(RBAC.equals(module)) {
            if(t.equals(r3.toLowerCase())) {
                strategy.setInclude(rbacTables);
                strategy.setTablePrefix("tb_");
            }else{
                strategy.setInclude(rbacViews);
            }
        }else if(PROD.equals(module)){
            if(t.equals(r3.toLowerCase())) {
                strategy.setInclude(prodTable);
                strategy.setTablePrefix("tb_");
            }else{
                strategy.setInclude(prodViews);
            }
        }
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.execute();
    }

}


/**
 * 自定义类型转换
 */
class MySqlTypeConvertCustom extends MySqlTypeConvert implements ITypeConvert {


    static final String TINYINT = "tinyint";
    @Override
    public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
        String t = fieldType.toLowerCase();
        if (t.contains(TINYINT)) {
            return DbColumnType.BYTE;
        }
        return super.processTypeConvert(globalConfig, fieldType);
    }
}

